#include <p32xxxx.h>
#include <plib.h>
#include "Bike_Display_HW_Profile.h"
#include "Bike_Display_UART_Functions.h"
#include "Bike_Display_ECM_Functions.h"



void UART5Init(void)
{
    // Configure the RS232 port to communicate with the bikes EMC
    UARTConfigure(UART5, UART_ENABLE_PINS_TX_RX_ONLY);
    UARTSetFifoMode(UART5, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
    UARTSetLineControl(UART5, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
    UARTSetDataRate(UART5, GetPeripheralClock(), 9600);
    UARTEnable(UART5, UART_ENABLE_FLAGS(UART_PERIPHERAL | UART_RX | UART_TX));

    // Configure UART5 RX Interrupt
    INTEnable(INT_SOURCE_UART_RX(UART5), INT_ENABLED);
    INTSetVectorPriority(INT_VECTOR_UART(UART5), INT_PRIORITY_LEVEL_2);
    INTSetVectorSubPriority(INT_VECTOR_UART(UART5), INT_SUB_PRIORITY_LEVEL_0);
}

// UART 5 interrupt handler, it is set at priority level 2
void __ISR(_UART_5_VECTOR, ipl2) IntUart5Handler(void)
{
    char c;
    char num_char = 0;

    // Is this an RX interrupt?
    if(INTGetFlag(INT_SOURCE_UART_RX(UART5)))
    {
        while(UARTReceivedDataIsAvailable(UART5))
        {
            //ReceiveData();
            //c = UARTGetDataByte(UART5);
            //ReceiveBuffer[num_char] = c;
            //num_char++;
            c = GetDataFromECM(ECMReceiveData, 255);
        }
        INTClearFlag(INT_SOURCE_UART_RX(UART5));
    }

    // We don't care about TX interrupt
    if ( INTGetFlag(INT_SOURCE_UART_TX(UART5)) )
    {
        INTClearFlag(INT_SOURCE_UART_TX(UART5));
    }
}

void UART1Init(void)
{
    // Configure the RS232 port for use with 4dSystem display
    UARTConfigure(UART1, UART_ENABLE_PINS_TX_RX_ONLY);
    UARTSetFifoMode(UART1, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
    UARTSetLineControl(UART1, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
    UARTSetDataRate(UART1, GetPeripheralClock(), 9600);
    UARTEnable(UART1, UART_ENABLE_FLAGS(UART_PERIPHERAL | UART_RX | UART_TX));

    // Configure UART1 RX Interrupt
    //INTEnable(INT_SOURCE_UART_RX(UART1), INT_ENABLED);
    //INTSetVectorPriority(INT_VECTOR_UART(UART1), INT_PRIORITY_LEVEL_3);
    //INTSetVectorSubPriority(INT_VECTOR_UART(UART1), INT_SUB_PRIORITY_LEVEL_0);
}

/*
// UART 1 interrupt handler
// it is set at priority level 3
void __ISR(_UART_1_VECTOR, ipl3) IntUart1Handler(void)
{
    // Is this an RX interrupt?
    if(INTGetFlag(INT_SOURCE_UART_RX(UART1)))
    {
        // Clear the RX interrupt Flag
        INTClearFlag(INT_SOURCE_UART_RX(UART1));
    }

    // We don't care about TX interrupt
    if ( INTGetFlag(INT_SOURCE_UART_TX(UART1)) )
    {
        INTClearFlag(INT_SOURCE_UART_TX(UART1));
    }
}
*/

void EnableInterrupts(void)
{
    // configure for multi-vectored mode
    INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
    // enable interrupts
    INTEnableInterrupts();
}

